package server;


import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import webWof.WebPlayer;


public class AddUserServlet extends HttpServlet {

	private static final long serialVersionUID = -7138184628829581896L;

	private int IDGenerator = 0;

	private synchronized int generateId(){
		return ++IDGenerator;
	}

	public AddUserServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setContentType("application/x-java-serialized-object");
			InputStream in = request.getInputStream();
			ObjectInputStream inputFromApplet = new ObjectInputStream(in);
			java.lang.Object o =  inputFromApplet.readObject();
			WebGamesManager manager = WebGamesManager.getInstance();
			WebPlayer newPlayer = (WebPlayer) o;
			int result;
			if (newPlayer.name.equalsIgnoreCase("Guest")){
				result = generateId();
				newPlayer.name += result;
				if (manager.CheckAndInsert(newPlayer, true) != 1)
					result = -1;	
			}
			else{
				result = manager.CheckAndInsert(newPlayer, false);	
			}

			OutputStream outstr = response.getOutputStream();
			ObjectOutputStream oos = new  ObjectOutputStream(outstr);
			oos.writeObject(result);
			oos.flush();
			oos.close();

		} catch (Exception e) { 
			e.printStackTrace();
		}		

	}



	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}




}
